<?php

namespace App\Service;

use OSS\OssClient;
use OSS\Core\OssException;

class OssService extends BaseService
{

	protected $accessKeyId;
	protected $accessKeySecret;
	protected $endpoint;
	protected $bucket;
	protected $ossClient;
   
	public function __construct()
	{
		$config = parent::getDi()['config'];
		$aliyuncs = $config->oss->aliyuncs;
		$this->accessKeyId = $aliyuncs->accessKeyId;
		$this->accessKeySecret = $aliyuncs->accessKeySecret;
		$this->endpoint = $aliyuncs->endpoint;
		$this->bucket = $aliyuncs->bucket;

		try {
		    $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
		} catch (OssException $e) {
		    var_dump($e->getMessage());
		}
	}

	public function uploadDir($dir = NULL)
	{
		$pic_path = "uploads/" . date("Y/m/d");
       	$doc_path = "uploads/files/" . date("Y/m/d");
		try{
			$pic_exist = $this->ossClient->doesObjectExist($this->bucket, $pic_path);
			$doc_exist = $this->ossClient->doesObjectExist($this->bucket, $doc_path);
			if (!$pic_exist)
	        	$pic_dir = $this->ossClient->createObjectDir($this->bucket, $pic_path);
	        if (!$doc_exist)
	        	$doc_dir = $this->ossClient->createObjectDir($this->bucket, $doc_path);
	    } catch(OssException $e) {
	        printf(__FUNCTION__ . ": FAILED\n");
	        printf($e->getMessage() . "\n");
	        return;
	    }
	}

	public function uploadFile($file, $key, $options = [])
	{
	    try{
	        $value = $this->ossClient->uploadFile($this->bucket, $key, $file);
	        return "/".$key;
	    } catch(OssException $e) {
	        throw new Exception($e->getMessage());
	    }
	}

}